package com.example.mqttdemo.config;

import com.example.mqttdemo.properties.MqttConfigurationProperties;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

@Configuration
public class MqttConfig {

    @Autowired
    private MqttConfigurationProperties mqttConfigurationProperties;

    @Bean
    public MqttConnectOptions mqttConnectOptions() {
        // 创建MqttConnectOptions对象
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        options.setUserName(mqttConfigurationProperties.getUsername());
        options.setPassword(mqttConfigurationProperties.getPassword().toCharArray());
        options.setServerURIs(new String[]{mqttConfigurationProperties.getUrl()});
        // 设置连接超时
        options.setConnectionTimeout(10);
        // 设置保持连接间隔
        options.setKeepAliveInterval(20);

        return options;
    }

    @Bean
    public MqttClient mqttClient(MqttConnectOptions options) {
        try {
            MqttClient client = new MqttClient(mqttConfigurationProperties.getUrl(), mqttConfigurationProperties.getPubClientId());
            client.connect(options);
            return client;
        } catch (MqttException e) {
            throw new RuntimeException("Failed to initialize MQTT client", e);
        }
    }

    /**
     * 创建并配置MQTT客户端工厂
     *
     * @return 配置好的MqttPahoClientFactory实例
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory(MqttConnectOptions options) {
        // 创建客户端工厂
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        // 设置MQTT连接选项
        factory.setConnectionOptions(options);
        // 返回
        return factory;
    }
}
